package com.beadwallet.alarm.web;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.beadwallet.alarm.service.msg.MsgInfoService;
import com.beadwallet.alarm.service.msg.MsgsendInfoService;
import com.beadwallet.alarm.service.msg.ShortMsgService;
import com.beadwallet.alarm.service.msg.TitleService;
import com.beadwallet.alarm.util.PropertiesUtil;
import com.beadwallet.alarm.entity.msgInfo.MsgInfo;
import com.beadwallet.alarm.entity.msgInfo.MsgsendInfo;
import com.beadwallet.alarm.util.SmsMD5Util;
import com.beadwallet.alarm.util.StringUtil;
import com.beadwallet.common.aspect.WebLog;
import com.beadwallet.common.controller.BaseController;
import com.beadwallet.common.enums.CodeEnum;
import com.beadwallet.common.utils.AlarmUtil;
import com.beadwallet.common.utils.HttpUtil;
import com.beadwallet.common.utils.MD5;
import io.swagger.annotations.Api;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

//import net.sf.json.JSONObject;


/**
 * @author xingx
 * @date 2017/12/8
 */
@RestController
@RequestMapping("shortMsg")
@Api(value = "shortMsg", description = "短信发送", tags = "shortMsg")
public class ShortMsgController extends BaseController {
    @Autowired
    private ShortMsgService shortMsgService;

    @Autowired
    private MsgsendInfoService iMsgsendInfoService;

    @Autowired
    private TitleService titleService;

    @Autowired
    private AlarmUtil alarmUtil;
    private static RequestConfig requestConfig;
    /**
     * 短信发送接口
     *
     * @return
     */

    /*@WebLog(description = "shortMsgSend")
    @PostMapping("shortMsgSend")
    @ResponseBody
    public String sendShortMsg(String jsonData) {
        try {
            log.warn("sendShortMsg jsonData:{}", jsonData);
            //将数据转化为Json类型
            JSONObject object = JSONObject.parseObject(jsonData);
            String type = object.getString("type");
            String templateId = object.getString("templateId");
            String mobiles = object.getString("mobiles");
            String parameters = object.getString("parameters");
            //调用发送短信方法
            String code = shortMsgService.send(type, templateId, mobiles, parameters);
            log.warn("code:{}", code);
            MsgsendInfo msgsendInfo = new MsgsendInfo();
            msgsendInfo.setSendData(jsonData);
            msgsendInfo.setCreateTime(new Date());
            msgsendInfo.setMobile(mobiles);
            msgsendInfo.setType(type);
            msgsendInfo.setTemplateid(templateId);
            //获取properties对象
            Properties properties = new Properties();
            try {
                properties.load(ShortMsgController.class.getResourceAsStream("/msg.properties"));
            } catch (IOException e) {
                e.printStackTrace();
            }
            String[] split = parameters.split(",");
            String property = String.format(properties.getProperty(templateId), split);
            log.warn("property:{}", property);
            msgsendInfo.setContent(property);
            if (code.equals(CodeEnum.SUCC.getCode())) {
                msgsendInfo.setStatus("ok");
                msgsendInfo.setSynchronization(0);
                log.warn("before insert");
                iMsgsendInfoService.insert(msgsendInfo);
                log.warn("end insert");
                return respJson(CodeEnum.SUCC);
            } else {
                msgsendInfo.setStatus("error");
                iMsgsendInfoService.insert(msgsendInfo);
                return respJson(CodeEnum.FAILURE);
            }
        }catch (Exception e) {
            alarmUtil.sendAlarm("ALARM", "发送野狗短信异常", e);
        }
        return null;
    }*/

    /*@WebLog(description = "shortMsgSend")
    @PostMapping("/shortMsgSend")
    public String shortMsgSend(String jsonData) {
        MsgsendInfo msgsendInfo = new MsgsendInfo();
        try {
            log.warn("jsonData:{}", jsonData);
            //获取jsonData中各个参数
            String mobiles = JSONObject.parseObject(jsonData).getString("mobiles");
            String[] mobile = mobiles.split(",");
            String regex = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0-9])|(17[1,3,5,6,7,8])|(19[8,9])|(16[6]))\\d{8}$";
            JSONObject dataObj = new JSONObject();
            String result = null;
            for (String s : mobile) {
                if(s.length() != 11){
                    return respJson(CodeEnum.PARAM_ERROR);
                }else{
                    Pattern p = Pattern.compile(regex);
                    Matcher m = p.matcher(s);
                    boolean isMatch = m.matches();
                    if(isMatch){
                        dataObj.put("phone", s);
                    } else {
                        return respJson(CodeEnum.PARAM_ERROR);
                    }
                    String parameters = JSONObject.parseObject(jsonData).getString("parameters");
                    String templateId = JSONObject.parseObject(jsonData).getString("templateId");
                    msgsendInfo.setSendData(jsonData);
                    msgsendInfo.setCreateTime(new Date());
                    msgsendInfo.setMobile(mobiles);
                    msgsendInfo.setTemplateid(templateId);
                    //加载msg.properties配置文件
                    Properties properties = PropertiesUtil.getProperties();
                    try {
                        properties.load(AlarmController.class.getResourceAsStream("/msg.properties"));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    String[] split = parameters.split(",");
                    String type ;
                    if (split.length <= 1) {
                        type = "code";
                        msgsendInfo.setType(type);
                    } else if (split.length <= 0) {
                        return respJson(CodeEnum.PARAM_ERROR);
                    } else {
                        type = "notify";
                        msgsendInfo.setType(type);
                    }
                    String msg = String.format(PropertiesUtil.getStringValue(templateId), split);
                    msgsendInfo.setContent(msg);
                    dataObj.put("msg", msg);
                    dataObj.put("type", "1");
                    dataObj.put("businessScenario", "1");
                    log.warn("dataObj:{}", dataObj);
                    String pk = MD5.genMd5("wYjitLLJKjaCNnMaSW5xEThD5KxtlOomMU07rZBIldLReCDw" + dataObj.toJSONString());
                    log.warn("pk:{}", pk);
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("pk", pk);
                    jsonObject.put("data", dataObj);
                    log.warn("jsonObject:{}", jsonObject);
                    HashMap<String, Object> map = new HashMap<>(16);
                    map.put("json", jsonObject);
                    result = HttpUtil.doPost(PropertiesUtil.getStringValue("short_msg_url"), map);
                    log.warn("result:{}", result);
                }
            }
            String requestCode = JSONObject.parseObject(result).getString("requestCode");
            String successCode = "200";
            if (successCode.equals(requestCode)) {
                msgsendInfo.setStatus("ok");
                msgsendInfo.setSynchronization(0);
                iMsgsendInfoService.insert(msgsendInfo);
                return respJson(CodeEnum.SUCC);
            } else {
                msgsendInfo.setStatus("error");
                iMsgsendInfoService.insert(msgsendInfo);
                return respJson(CodeEnum.FAILURE);
            }
        } catch (Exception e) {
            alarmUtil.sendAlarm("ALARM", "发送短信异常", e);
        }
        msgsendInfo.setStatus("error");
        iMsgsendInfoService.insert(msgsendInfo);
        return respJson(CodeEnum.FAILURE);
    }*/

    @Autowired
    private MsgInfoService msgInfoService;

    /**
     * 调取武汉接口发送短信
     */
    @WebLog(description = "shortMsgSend")
    @PostMapping("/shortMsgSend")
    public String shortMsgSend(String jsonData) {
        MsgsendInfo msgsendInfo = new MsgsendInfo();
        ResourceBundle bundle = ResourceBundle.getBundle("msg");
        try {
            log.warn("jsonData:{}", jsonData);
            //获取jsonData中各个参数
            String mobiles = JSONObject.parseObject(jsonData).getString("mobiles");
            String type = JSONObject.parseObject(jsonData).getString("type");
            String[] mobile = mobiles.split(",");
            JSONObject dataObj = new JSONObject();
            String result = null;
            //判断手机号是否合法
            for (String s : mobile) {
                if (s.length() != 11) {
                    return respJson(CodeEnum.PARAM_ERROR);
                } else {
                    dataObj.put("phone", s);
                    String parameters = JSONObject.parseObject(jsonData).getString("parameters");
                    String templateId = JSONObject.parseObject(jsonData).getString("templateId");
                    msgsendInfo.setSendData(jsonData);
                    msgsendInfo.setCreateTime(new Date());
                    msgsendInfo.setMobile(mobiles);
                    msgsendInfo.setTemplateid(templateId);
                    //将参数以逗号分隔开
                    String[] split = parameters.split(",");
                    if ("code".equals(type)) {
                        msgsendInfo.setType("code");
                    } else {
                        msgsendInfo.setType("notify");
                    }
                    //根据templateId查询短信模板
                    Wrapper<MsgInfo> msgInfoEntityWrapper = new EntityWrapper<>();
                    msgInfoEntityWrapper.eq("template_id", templateId);
                    List<MsgInfo> msgInfos = msgInfoService.selectList(msgInfoEntityWrapper);
                    String msg;
                    for (MsgInfo msgInfo : msgInfos) {
                        msg = String.format(msgInfo.getMsgContent(), split);
                        //转码
                        String msgContent = URLDecoder.decode(msg, "UTF-8");
                        msgsendInfo.setContent(msgContent);
                        dataObj.put("msg", msgContent);
                    }
                    dataObj.put("type", "1");
                    dataObj.put("businessScenario", "1");
                    //MD5加密
                    String pk = MD5.genMd5(bundle.getString("key") + dataObj.toJSONString());
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("pk", pk);
                    jsonObject.put("data", dataObj);
                    log.warn("jsonObject:{}", jsonObject);
                    HashMap<String, Object> map = new HashMap<>(16);
                    map.put("json", jsonObject);
                    //调用发送短信的接口
                    result = HttpUtil.doPost(bundle.getString("short_msg_url"), map);
                    log.warn("result:{}", result);
                    msgsendInfo.setUpdateTime(new Date());
                }
            }
            //解析返回码
            String requestCode = JSONObject.parseObject(result).getString("requestCode");
            String successCode = "200";
            String message = parseReturnCode(successCode, requestCode, msgsendInfo);
            return message;
        } catch (Exception e) {
            alarmUtil.sendAlarm("ALARM", "发送短信异常", e);
        }
        msgsendInfo.setStatus("error");
        iMsgsendInfoService.insert(msgsendInfo);
        return respJson(CodeEnum.FAILURE);
    }

    @WebLog(description = "mallMsgSend")
    @PostMapping("/mallMsgSend")
    public String mallMsgSend(String json) {
        MsgsendInfo msgsendInfo = new MsgsendInfo();
        int mobileNum = 11;
        String result;
        ResourceBundle bundle = ResourceBundle.getBundle("msg");
        try {
            JSONObject dataObj = new JSONObject();
            msgsendInfo.setCreateTime(new Date());
            String mobile = JSONObject.parseObject(json).getString("mobile");
            String content = JSONObject.parseObject(json).getString("content");
            String source = JSONObject.parseObject(json).getString("source");
            if (StringUtil.isEmpty(mobile) || StringUtil.isEmpty(content) || StringUtil.isEmpty(source)) {
                return respJson(CodeEnum.PARAM_ERROR, "参数格式不正确！");
            } else {
                msgsendInfo.setMobile(mobile);
                if (mobile.length() != mobileNum) {
                    return respJson(CodeEnum.PARAM_ERROR);
                } else {
                    dataObj.put("phone", mobile);
                }
                dataObj.put("msg", content);
                msgsendInfo.setContent(content);
                dataObj.put("type", "1");
                msgsendInfo.setType("code");
                dataObj.put("businessScenario", 1);
                //MD5加密
                String secretKey = MD5.genMd5(bundle.getString("key") + dataObj.toJSONString());
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("secretkey", secretKey);
                jsonObject.put("data", dataObj);
                log.warn("jsonObject:{}", jsonObject);
                //调用发送短信的接口
                result = this.doPost(bundle.getString("mall_msg_url"), jsonObject.toString(), null);
                log.warn("mall msg result:{}", result);
                msgsendInfo.setUpdateTime(new Date());
                msgsendInfo.setChannel(source);
                //解析返回码
                String requestCode = JSONObject.parseObject(result).getString("requestCode");
                String successCode = "0000";
                String message = parseReturnCode(successCode, requestCode, msgsendInfo);
                return message;
            }
        } catch (Exception e) {
            alarmUtil.sendAlarm("ALARM", "商城发送短信错误", e);
        }
        msgsendInfo.setStatus("error");
        iMsgsendInfoService.insert(msgsendInfo);
        return respJson(CodeEnum.FAILURE);
    }

    /**
     * 解析返回码
     *
     * @param returnCode
     * @param msgsendInfo
     * @return
     */
    private String parseReturnCode(String successCode, String returnCode, MsgsendInfo msgsendInfo) {
        if (successCode.equals(returnCode)) {
            msgsendInfo.setStatus("ok");
            msgsendInfo.setSynchronization(0);
            iMsgsendInfoService.insert(msgsendInfo);
            return respJson(CodeEnum.SUCC);
        } else {
            msgsendInfo.setStatus("error");
            iMsgsendInfoService.insert(msgsendInfo);
            return respJson(CodeEnum.FAILURE);
        }
    }


    public String doPost(String apiUrl, String param, Header header) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String httpStr = null;
        HttpPost httpPost = new HttpPost(apiUrl);
        CloseableHttpResponse response = null;

        try {
            httpPost.setHeader("Content-type", "application/json; charset=utf-8");
            httpPost.setConfig(requestConfig);
            StringEntity stringEntity = new StringEntity(param, "UTF-8");
            stringEntity.setContentEncoding("UTF-8");
            httpPost.setEntity(stringEntity);
            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            httpStr = EntityUtils.toString(entity, "UTF-8");
        } catch (IOException var17) {

        } finally {
            if (response != null) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException var16) {

                }
            }

        }
        return httpStr;
    }
}